import http from '@/utils/request'
import { setTokenInfo } from '@/utils/storage'

import { Appdispatch } from '..'
import { ActionType, PersonData } from '../reducer/user'
/**
 * @param mobile 手机号 发送短信验证
 * @returns
 */
export function sendCodeRegxFn(mobile: string) {
  return async (dispatch: Appdispatch) => {
    const res = await http.get(`/v1_0/sms/codes/${mobile}`)
  }
}

/**
 @param 用户登录认证 {mobile,code}
 *@returns
 * ****/
export function AuthorizationsFn({ mobile, code }: { mobile: string; code: string }) {
  return async (dispatch: Appdispatch) => {
    const res = await http.post('/v1_0/authorizations', { mobile, code })

    dispatch({ type: 'user/getUserToken', payload: res.data })
    // 保存token
    setTokenInfo(res.data)
  }
}

/**
 * @param 获取用户的信息
 * @returns
 */

export function getUserinfo() {
  return async (dispatch: Appdispatch) => {
    const res = await http.get('/v1_0/user')
    console.log(res.data)

    dispatch({ type: 'user/getuserInfo', payload: res.data })
  }
}

/**
 * @param 获取个人资料
 * @returns
 */
export function getPersonData() {
  return async (dispatch: Appdispatch) => {
    const res = await http.get('/v1_0/user/profile')
    console.log('/v1_0/user/profile', res.data)
    dispatch({ type: 'user/getPersonData', payload: res.data })
  }
}

/**
 * @param 编辑用户照片资料（头像、身份证照片）Path： /v1_0/user/photo Method： PATCH
 * @returns
 */
export function updatePersonPhoto(pt: FormData) {
  return async (dispatch: Appdispatch) => {
    const res = await http.patch('/v1_0/user/photo', pt)
    console.log(res)

    dispatch({ type: 'user/updatePersonImg', payload: res.data })
  }
}

/**
 * @param 编辑用户个人资料  Path： /v1_0/user/profile  Method： PATCH
 * @returns
 */
export function editPersonProflie(data: Partial<PersonData>) {
  return async (dispatch: Appdispatch) => {
    await http.patch('/v1_0/user/profile', data)
    dispatch({ type: 'user/updateUserProfile', payload: data })
  }
}

/**
 * @param 退出 清除用户的token 清除redux中的信息
 * @returns
 */
export function signoutFn(): ActionType {
  return { type: 'user/clearAuth' }
}
